package webdev.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import webdev.danagtravel.PlaceDetailActivity;
import webdev.database.SQLQuery;
import webdev.dto.DiaDiemDTO;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import dev.danang.R;

public class MapPlacesFragment extends BaseFragment implements OnInfoWindowClickListener {
	
	public static final String TAG = MapPlacesFragment.class.getSimpleName();
	
	private int index;
	
	private View view = null;
	private LayoutInflater mLayoutInflater;
	
	// Fragment
	FragmentManager fmanager;
	Fragment fragment;
	SupportMapFragment supportmapfragment;
	
	// GoogleMap
	private GoogleMap gMap;

	private ArrayList<DiaDiemDTO> mPlaces;
	private Map<Marker, DiaDiemDTO> allMarkers = new HashMap<Marker, DiaDiemDTO>();
	
	// AsyncTask
	private LoadData mLoadData;
	
	/**
	 * @param index
	 * index de nhan biet thuoc menu nao
	 * @return
	 */
	public static MapPlacesFragment newInstance(int index) {
		MapPlacesFragment mapPlaces = new MapPlacesFragment();
		Bundle args = new Bundle();
		args.putInt("index", index);
		mapPlaces.setArguments(args);
        return mapPlaces;
    }
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mLayoutInflater = inflater;
		if(view == null) {
			try {
				view = mLayoutInflater.inflate(R.layout.fragment_map, container,false);
			} catch (InflateException e) {
				e.printStackTrace();
			}
		} else {
			ViewGroup parent = (ViewGroup) view.getParent();
			if(parent != null) {
				parent.removeView(view);
			}
		}
		
		init(view);
		setValueForMembers();
		setEventForMembers();
		mLoadData = new LoadData(getActivity());
		mLoadData.execute();
		
		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	}
	
	@Override
	protected void init(View layout) {
		
		index = getArguments().getInt("index");
		
		mPlaces = new ArrayList<DiaDiemDTO>();
		
		// Map
		if(gMap == null) {
			fmanager = getFragmentManager();
			fragment = fmanager.findFragmentById(R.id.map_fragment);
			supportmapfragment = (SupportMapFragment)fragment;
			gMap = supportmapfragment.getMap();
		}
	}

	@Override
	protected void setValueForMembers() {
	}

	@Override
	protected void setEventForMembers() {
		gMap.setOnInfoWindowClickListener(this);
	}

	@Override
	protected String getUrl() {
		// TODO Auto-generated method stub
		return null;
	}
	
	private void setMap() {
		LatLng POINT_PLACE = new LatLng(0, 0);
		int leng = mPlaces.size();
		for(int i = 0 ; i < leng ; i++) {
			POINT_PLACE  = new LatLng(mPlaces.get(i).getLat(),mPlaces.get(i).getLng());
			Marker mMaker = gMap.addMarker(new MarkerOptions()
			.position(POINT_PLACE)
			.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
			.title(mPlaces.get(i).getTitle()));
			allMarkers.put(mMaker, mPlaces.get(i));
		}
		CameraUpdate cameraUpdate;
		cameraUpdate = CameraUpdateFactory.newLatLngZoom(POINT_PLACE, 12);
		gMap.moveCamera(cameraUpdate);
		gMap.setMyLocationEnabled(true);
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if(fragment != null) {
			getFragmentManager().beginTransaction().remove(fragment).commit();
		}
		
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		if(fragment != null) {
			getFragmentManager().beginTransaction().remove(fragment).commit();
		}
	}
	
	/**
	 * Class Asynctask load data
	 */
	private class LoadData extends AsyncTask<Void, Void, Boolean> {
		
		private ArrayList<DiaDiemDTO> places;
		
		private SQLQuery db;
		
		public LoadData(Context context) {
			places = new ArrayList<DiaDiemDTO>();
			db = new SQLQuery(context);
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		
		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				
				/**
				 * index == 0 --> Load destination
				 * index == 1 --> Load hotel
				 * index == 2 --> Load travel
				 * index == 3 --> Load cuisine
				 * index == 4 --> Load entertainment
				 */
				if (index == 0 ) {
					places = db.getAllDiaDiem(SQLQuery.TYPE_PLACE);
				} else if (index == 1) {
					places = db.getAllDiaDiem(SQLQuery.TYPE_HOTEL);
				} else if (index == 2) {
					places = db.getAllDiaDiem(SQLQuery.TYPE_LU_HANH);
				} else if (index == 4) {
					places = db.getAllDiaDiem(SQLQuery.TYPE_RELAX);
				}
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			return false;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			if(result) {
				mPlaces = places;
				setMap();
			}
		}
	}

	@Override
	public void onInfoWindowClick(Marker marker) {
		Intent goToDetailPlace = new Intent(getActivity(), PlaceDetailActivity.class);
		Bundle bundle = new Bundle();
		bundle.putParcelable("places", allMarkers.get(marker));
		goToDetailPlace.putExtras(bundle);
		getActivity().startActivity(goToDetailPlace);
	}
	
}
